const str = 'Hello, World!';

// slice
// 截取字符串，返回一个新的字符串
String.prototype.sx_slice = function (start = 0, end) {
    start = start < 0 ? this.length + start : start;
    end = !end && end !== 0 ? this.length : end;

    if (start >= end) return '';
    let str = '';
    for (let i = start; i < end; i++) {
        str += this[i];
    }

    return str;
}

console.log('sx_slice:');
console.log(str.sx_slice(2));
console.log(str.sx_slice(-2));
console.log(str.sx_slice(-9, 10));
console.log(str.sx_slice(5, 1));

// substr
String.prototype.sx_substr = function (start = 0, length) {
    if (length < 0) return '';

    start = start < 0 ? this.length + start : start;
    length = (!length && length !== 0) || length > this.length - start ? this.length : start + length;

    let str = '';
    for (let i = start; i < length; i++) {
        str += this[i];
    }
    return str;
}

console.log('substr:');
console.log(str.sx_substr(3));
console.log(str.sx_substr(3, 3));
console.log(str.sx_substr(5, 300));

// substring
String.prototype.sx_substring = function (start = 0, end) {
    start = start < 0 ? this.length + start : start;
    end = !end && end !== 0 ? this.length : end;

    if (start >= end) [start, end] = [end, start]; // es6的特性交互
    let str = '';
    for (let i = start; i < end; i++) {
        str += this[i];
    }

    return str;
}

console.log('substring:');
console.log(str.sx_substring(2));
console.log(str.sx_substring(-2));
console.log(str.sx_substring(-9, 10));
console.log(str.sx_substring(5, 1));